/**
 * 版权所有(C)，上海海鼎信息工程股份有限公司，2020，所有权利保留。
 * <p>
 * 项目名：	sop-commons
 * 文件名：	Watcher.java
 * 模块说明：
 * 修改历史：
 * 2020/8/25 - zhuchao - 创建。
 */
package com.lovely602.boot.bootdemo.domain.common.log;

import org.springframework.util.StopWatch;

/**
 * 性能监控
 * 
 * @author lizhixing
 */
public class Watcher {
  private static final ThreadLocal<StopWatch> holder = new ThreadLocal<>();

  private Watcher() {

  }

  public static void createWatcher(String task) {
    holder.set(new StopWatch(task));
  }

  public static void watchTimeout(String taskName, Long timeout) {
    StopWatch stopWatch = holder.get();
    long totalTimeMillis = stopWatch.getTotalTimeMillis();
    if (timeout != null && timeout != 0L && totalTimeMillis > timeout) {
      throw new WatchException();
    }
    watch(taskName, stopWatch);
  }

  public static void watch(String taskName) {
    StopWatch stopwatch = holder.get();
    if (stopwatch == null) {
      holder.set(new StopWatch());
      stopwatch = holder.get();
    }
    if (stopwatch.isRunning()) {
      stopwatch.stop();
    }
    stopwatch.start(taskName);
  }

  public static void watch(String taskName, StopWatch watch) {
    if (watch.isRunning()) {
      watch.stop();
    }
    watch.start(taskName);
  }

  public static String detail() {
    StopWatch stopwatch = holder.get();
    if (stopwatch.isRunning()) {
      stopwatch.stop();
    }
    return stopwatch.prettyPrint();
  }

  public static void clear() {
    holder.remove();
  }
}
